package org.lc.platform.base.dto;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Min;
import lombok.Data;

import java.util.Arrays;

@Data
public class PageQuery {

    @Min(value = 1, message = "页码必须大于1")
    @Schema(description = "页码", type = "int", example = "1", requiredMode = Schema.RequiredMode.REQUIRED)
    private Integer pi = 1;

    @Min(value = 1, message = "数量必须大于1")
    @Schema(description = "数量", type = "int", example = "10", requiredMode = Schema.RequiredMode.REQUIRED)
    private Integer ps = 10;


    @Schema(description = "是否需要分页", type = "boolean", defaultValue = "true")
    private Boolean isPage = true;

    @Schema(description = "排序字段,多字段使用,隔开", type = "string", defaultValue = "createTime")
    private String sortBy;

    @Schema(description = "是否升序,多字段使用,隔开", type = "string", defaultValue = "true")
    private String isAsc = "true";

    @Schema(description = "关联字段", type = "string")
    private String join;


    public <T> Page<T> toMapPage(OrderItem... item) {
        Page<T> page = Page.of(pi, ps);
        if (StrUtil.isNotBlank(sortBy)) {
            String[] sorts = sortBy.contains(",") ? sortBy.split(",") : new String[]{sortBy};
            String[] asks = isAsc.contains(",") ? isAsc.split(",") : new String[]{isAsc};
            for (int i = 0; i < sorts.length; i++) {
                boolean asc = true;
                try {
                    asc = Boolean.parseBoolean(Arrays.stream(asks).toList().get(i));
                } catch (Exception e) {
                    System.err.println(e.getMessage());
                }
                page.addOrder(new OrderItem(StrUtil.toUnderlineCase(sorts[i]), asc));
            }
        } else if (item != null) {
            page.addOrder(item);
        } else {
            page.addOrder(new OrderItem("create_time", false));
        }
        return page;
    }

    public <T> Page<T> toMapPage(String sortBy, Boolean asc) {
        return toMapPage(new OrderItem(sortBy, asc));
    }

    public <T> Page<T> toMapPageDefaultSortByCreateTime() {
        return toMapPage(new OrderItem("create_time", false));
    }

    public <T> Page<T> toMapPageDefaultSortByUpdateTime() {
        return toMapPage(new OrderItem("update_time", false));
    }
}
